//载入那些函数库
let includes = ([
    "include/common.js",
]);

//继承哪些JS 在所有代码之前要完成继承
let inherits = ([
    "inherit/data.js",
    "inherit/room/sim.js",
    "inherit/save.js"
]);


let vars = {
    timer: 0,
    ownUser: 0,
    //事件
    events: {
        //抢劫
        qiangjie: {
            name: "抢劫",
            //事件描述
            desc: ["你小子真不走运，又被抢劫了"],
        },
        //离职
        lizhi: {
            name: "人资",
            desc: ["这儿美女太少，大家都吵扰着离开了"]
        },
        //娱乐实施
        yule: {
            name: "娱乐",
            desc: ["天天干活儿，都没有玩的地方"]
        },
        //电力
        dianli: {
            name: "电力",
            desc: ["供电不足，该想想办法了..."]
        }

        //人口

    }
};


let homes = [];
let homeData = {
    id: "",
    //等级
    lv: 1,
    //人口
    ppCount: 0,
    //满意度
    satisfaction: 10,
    type: "home",
};


//电站数据结构
let dianzhan = {
    id: "",
    //等级
    lv: 1,
    type: "dian",
};


vars.cityData = {
    //人民满意度
    ppSatis: 5,
    //总的电力
    dian: 0,
    //土地
    land: {
        //土地上的建筑
        build: [],
        //土上的生物
        biolo: [],
    },

    //仓库存储
    storage:{
        res:{

        }
    }

};


/**
 * 电力消耗算法
 * 电
 * 人口 / 2
 * -----------------------------------
 * 小型风力发电站 2000  10点电力
 * 中型风力发电站 5000  50点电力
 * @returns {*}
 */



//被创建的时候触发
function create() {
    let me = thisObject;
    me.set("name", "模拟城市");
    me.set("desc", `这是一个模拟城市.....`);
    //是否是玩家
    me.set("obType", "isRoom");
    me.set("heartbeat", true);

    me.set("min", 20);
    //资源上限
    me.set("resLimit", 20);
    me.set("ownUser", "");
    me.set("timer", 0);
    me.set("res", 20);

    //事件记录....
    me.set("roomEventListLog", {});


    me.set("exits", {
        south: "d/chengdu/guangchang.js",
    });


    me.set("cmds", {
        start: start,
        //创建住宅
        cr: createOb,
        //查看
        ls: list,

    })

    return me;
}


/**
 *  res 资源存储类建筑
 * combat 战斗类
 * combatType 战斗类型 attack攻击 def防御
 * resbuild 可产出资源的建筑
 *
 *
 * 攻击频率
 *
 *
 *
 * @param caller
 * @param arg
 */

vars.simConf = {

    builds: {
        "100001": {
            id: 100001,
            name: "部落中心",
            canCombat: false,
            outType: "none",
            type: "build",
        },

        "100020": {
            id: 100020,
            lv: 1,
            //最大容量
            cap: 2000,
            //当前存储数量
            size: 0,
            //资源类
            outType: "res",
            name: "金库",
            canCombat: false,
            type: "build",
        },

        "100021": {
            id: 100021,
            lv: 1,
            cap: 3500,
            name: "粮仓",
            outType: "none",
            canCombat: false,
            type: "build",
        },

        //可产出黄金和矿石
        "100022": {

            id: 100022,

            lv: 1,

            //产出需要耗时
            prodTime: 1,

            //重计时间
            prodStartTime: 0,

            //产出资源 1黄金 2 矿石
            res: {
                gold: {
                    name: "金币",
                    rd: [2, 3],
                },
                stone: {
                    name: "矿石",
                    rd: [2, 4],
                }
            },

            //产出类型 res 资源
            outType: "res",

            canCombat: false,
            name: "矿场",
            type: "build",
        },

        "100023": {
            id: 100023,
            lv: 1,
            //最低等级容量
            cap: 20,
            name: "兵营",
            //cmbUnits 战斗单位
            outType: "none",
            canCombat: false,
            type: "build",
        },

        //存储石头用
        "100024": {
            id: 100024,
            lv: 1,
            cap: 2000,
            name: "聚石塔",
            outType: "none",
            canCombat: false,
            type: "build",
        },
        "100025": {
            id: 100025,
            lv: 1,
            hp: 80,
            attack: 10,
            def: 5,
            name: "炮台",
            outType: "none",
            canCombat: true,
            type: "build",
        },

        "100026": {
            id: 100026,
            lv: 1,
            //产出需要耗时
            prodTime: 60,
            //重计产出时间
            prodStartTime: 0,
            res: {
                gra: {
                    name: "粮食",
                    rd: [3, 5],
                },
            },
            def: 5,
            canCombat: false,
            name: "农场",
            outType: "res",
            type: "build",
        },

        "100027": {
            id: 100027,
            lv: 1,
            //产出需要耗时
            prodTime: 60,
            //重计产出时间
            prodStartTime: 0,
            def: 5,
            name: "训练营",
            canCombat: false,
            outType: "cmbUnits",
            type: "build",
        },
        "100028": {
            id: 100028,
            lv: 1,
            def: 5,
            name: "住宅",
            canCombat: false,
            outType: "none",
            type: "build",
        },
        //--------------------------------------------资源物品
        "100060": {
            id: 100060,
            lv: 1,
            def: 5,
            name: "香料",
            canCombat: false,
            outType: "none",
            type: "res",
        },

        "100061": {
            id: 100061,
            lv: 1,
            def: 5,
            name: "小麦",
            canCombat: false,
            outType: "none",
            type: "res",
        },

        "100062": {
            id: 100062,
            lv: 1,
            def: 5,
            name: "面包",
            canCombat: false,
            outType: "none",
            type: "res",
        },

        "100063": {
            id: 100063,
            lv: 1,
            def: 5,
            name: "木头",
            canCombat: false,
            outType: "none",
            type: "res",
        },


        "100100": {
            id: 100100,
            lv: 1,
            sid: "",
            hp: 35,
            def: 10,
            attack: 12,
            name: "刺客",
            canCombat: true,
            type: "biolo",
        },

        "100101": {
            id: 100101,
            //唯一的随机编号
            sid: "",
            lv: 1,
            hp: 50,
            def: 18,
            attack: 8,
            name: "象甲兵",
            canCombat: true,
            type: "biolo",
        },
    }
}


function createOb(caller, arg) {
    let me = thisObject;
    // let data = vars.simConf.builds[arg];
    //必须复制....
    var data = JSON.parse(JSON.stringify(vars.simConf.builds[arg]));

    if (arg.startsWith("1001")) {
        data.sid = os.util.random.randomSid();
        vars.cityData.land.biolo.push(data);
        return;
    }

    if (arg == "100022") {
        if (getAllGoldContainers().length <= 0) {
            me.sendOwn("先创建金库才能创建矿场呀！");
            return;
        }
    }
    vars.cityData.land.build.push(data);
    me.sendOwn(data.name + " 创建成功！");
}

/**
 * 获取可攻击的战斗单位
 */
function getAttackUnit() {
    let unit = vars.cityData.land.biolo;
    unit = unit.filter(e => {
        return e.hp > 0;
    })

    return unit;
}


function list(caller, arg) {

    let me = thisObject;
    os.debug(arg, "list cmd");

    if (arg == "pps") {//查看人口
        me.sendOwn("当前的总人口数量是" + me.getAllPpCount());
    } else if (arg == "homes") {

    } else if (arg == "golds") {
        let goldContiners = getAllGoldContainers();
        let str = "当前金库情况:\n";
        goldContiners.forEach(e => {
            str += `${e.name}: ${e.size}/${e.cap}\n`;
        });
        me.sendOwn(str);
    } else if (arg == "cmbls") {//查看战斗单位
        let str = "当前的战斗单位有:\n";
        vars.cityData.land.biolo.forEach(e => {
            if (e.type == "biolo" && e.canCombat) {
                str += `血量:${e.hp} 攻击:${e.attack} 防御:${e.def}\n`;
            } else {
                str += `血量:${e.hp} 攻击:0 防御:${e.def}\n`;
            }
        });
        me.sendOwn(str);
    }
}


/**
 * 获取黄金总的存量
 */
function getGoldCap() {

    let goldPors = vars.cityData.land.build.filter(e => {
        return e.id == 100020;
    });
    //最低500容量...
    if (goldPors.length <= 0) return 500;
    let caps = 0;
    goldPors.forEach(e => {
        caps += e.cap;
    });
    return caps;
}

/**
 * 获取可以使用的黄金容器
 * @returns {number}
 */
function getGoldContainer() {

    let goldPors = vars.cityData.land.build.filter(e => {
        return e.id == 100020 && e.size < e.cap;
    });

    if (goldPors.length <= 0) return false;
    return goldPors;
}

/**
 * 获取所有的金库
 * @returns {T[]}
 */
function getAllGoldContainers() {
    let goldPors = vars.cityData.land.build.filter(e => {
        return e.id == 100020;
    });
    return goldPors;
}


/**
 * 增加黄金
 * @param n
 */
function addGold(n) {
    let continers;
    if ((continers = getGoldContainer()) == false) {
        sendOwn("没有可用的金库，或所有的金库都已经满载。")
        return;
    }
    continer = getRandomOneOfArr(continers);
    continer.size += n;
}


//获取所有住宅
function getHomes() {
    let homes = vars.cityData.land.build.filter(e => {
        return e.type == "home";
    });
    return homes;
}


function getDianzhans() {
    let dianz = vars.cityData.land.build.filter(e => {
        return e.type == "dian";
    });
    return dianz;
}

//获取总的电力
function getOutDian() {
    let d = 0;
    getDianzhans().forEach(e => {
        d += e.out;
    })
    return d;
}


function getAllPpCount() {
    let count = 0;
    getHomes().forEach(e => {
        count += e.ppCount;
    })
    return count;
}


function start(caller, arg) {

    let me = thisObject;

    if (objectp(me.get("ownUser"))) {
        tellObject(caller, "知道什么叫名矿有主吗？").to();
        return;
    }

    if (!objectp(me.get("ownUser"))) {
        me.set("ownUser", caller);
        me.vars.ownUser = caller;
        caller.set("simOb", thisObject);
        tellObject(caller, "遥远的天际，一个神秘的部落诞生了。").to();
        return;
    }
}


function sendOwn(msg) {
    let me = thisObject;
    if (objectp(me.get("ownUser"))) {
        tellObject(me.get("ownUser"), msg).to();
        return;
    }
}


function addRes(d) {
    let me = thisObject;
    let res = me.get("res");
    res += d;
    me.set("res", res);
    tellObject(me.get("ownUser"), `你的矿石增加了，当前有${res}个..`).to();
}

function getEvent() {

    let me = thisObject;
    let r = random(0, 100);
    let l = random(0, 100);
    // os.debug(r,"debuger");
    // os.debug(r,"随机数");
    if (r < 10 && l < 10) {
        let desc, eventSize = Object.keys(me.vars.events).length;
        let eventKes = Object.keys(me.vars.events);
        let k = getRandomOneOfArr(eventKes);
        tellObject(me.get("ownUser"), `系统选中了${me.vars.events[k].name}事件`).to();
        desc = getRandomOneOfArr(me.vars.events[k].desc);
        tellObject(me.get("ownUser"), `${desc}`).to();
    }
}


function doBuild() {

    vars.cityData.land.build.forEach(e => {
        if (e.type == "build" && e.outType == "res" && !undefinedp(e.res)) {
            if (e.prodStartTime < e.prodTime) {
                e.prodStartTime++;
            } else {
                e.prodStartTime = 0;
                let resKeys = Object.keys(e.res);
                let resKey, resn = getRandomOneOfArr(resKeys);
                resKey = resn;

                resn = e.res[resn];
                let c = random(resn.rd[0], resn.rd[1]);
                os.debug(resKey, "当前资源key")
                if (resKey == "gold") {
                    addGold(c);
                }

                sendOwn(e.name + "产出" + resn.name + " " + c + " 个");

            }
        }
    })


}

function heartbeat() {


    let me = thisObject;



    if( !objectp(me.get("ownUser")) ) return ;


    me.save();


    if (!objectp(me.get("ownUser"))) return;


    if (me.vars.timer <= 0) {
        me.vars.timer = new Date().getTime();
    }

    let diffTime = new Date().getTime() - me.vars.timer;
    diffTime = timeDuring(diffTime, "s");

    //时间间隔处理
    if (diffTime < 1) {
        return;
    }

    me.vars.timer = new Date().getTime();
    os.debug("---------------------------dobuild");
    doBuild();


    //
    // // me.save();
    // me.vars.timer = new Date().getTime();


    // me.getEvent();
    // me.sendOwn(`时间过去了${diffTime}s`);
    // me.addRes(1);

    //随机增加人口


    // let r = random(0, 100);
    // let homes = getHomes();
    // if (r < 50 && homes.length > 0) {
    //     let idx = random(0, homes.length - 1);
    //     if (homes[idx].ppCount < homes[idx].maxppCount) {
    //         homes[idx].ppCount += 1;
    //         me.sendOwn(homes[idx].name + "的人口增加了");
    //     }
    // }
    //
    // let costDian = getAllPpCount() / 2;
    //
    // let allDian = getOutDian();
    // if (allDian < costDian) {
    //     me.sendOwn("电力不足...");
    // }
    //
    // me.sendOwn(`用电情况${costDian}/${allDian}`);


    return false;
}



function save() {
    let me = thisObject;

    pub.data = vars.cityData;


    $$(me).save();
}


function querySaveFile() {
    return "data/game/sim/" + thisObject.vars.ownUser.get("id");
}




